package Stages

import Actors.Mario
import TouchState
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import floatHeight
import image
import setOnTouchListener
import stageFlag

/**
 * 游戏舞台
 */
class GameStage : Stage()
{
    // 原始图像
    private val img by lazy { TextureRegion(Texture(Gdx.files.internal("mario.png"))) }
    // 切割原始图像
    private val imgs by lazy { img.split(64, 64) }
    // 切割翻转原始图像
    private val flipImgs by lazy {
        img.split(64, 64).apply {
            forEach {
                it.forEach {
                    it.flip(true, false)
                }
            }
        }
    }

    // 左边按钮
    private val leftBtn by lazy { ImageButton(TextureRegionDrawable(imgs[1][0]), TextureRegionDrawable(imgs[1][1])) }
    // 右边按钮
    private val rightBtn by lazy { ImageButton(TextureRegionDrawable(flipImgs[1][0]), TextureRegionDrawable(flipImgs[1][1])) }
    // 马里奥对象
    private val mario by lazy { Mario(0f, 50f, imgs, flipImgs) }
    // 背景图片
    private val image by lazy {
        image("bg.jpg").apply {
            height = Gdx.graphics.floatHeight
        }
    }

    private val shopBtn by lazy { image("shop_btn.png") }
    
    init
    {
        shopBtn.translate(Gdx.graphics.width - shopBtn.width - 10, Gdx.graphics.height - shopBtn.height - 10)
        shopBtn.setOnTouchListener { _, touchState ->
            if (touchState == TouchState.touchUp)
            {
                stageFlag = MainPage.STAGE_FLAG.STORE
            }
        }


        rightBtn.setPosition(64f, 0f)
        leftBtn.setOnTouchListener { _, touchState ->
            when (touchState)
            {
                TouchState.touchDown ->
                {
                    mario.state = Mario.STATE.LEFT
                }
                TouchState.touchUp ->
                {
                    mario.state = Mario.STATE.LEFT_IDLE
                }
            }
        }
        rightBtn.setOnTouchListener { _, touchState ->
            when (touchState)
            {
                TouchState.touchDown ->
                {
                    mario.state = Mario.STATE.RIGHT
                }
                TouchState.touchUp ->
                {
                    mario.state = Mario.STATE.RIGHT_IDLE
                }
            }
        }

        this.addActor(image)
        this.addActor(leftBtn)
        this.addActor(rightBtn)
        this.addActor(mario)
        this.addActor(shopBtn)
    }
    
    
    
}